﻿using System;
using System.Windows.Controls.Primitives;
using System.Data.Services.Client;
using Coevery.ViewModel.EntityDataService;
using System.Linq;

namespace Coevery.ViewModel
{
    public class ContractViewModel:BaseViewModel
    {
        public Guid ContractId { get; set; }
        public Popup Popup { get; set; }
        public event EventHandler EnableButton;

        private DataServiceCollection<Contract> _contracts;

        public DataServiceCollection<Contract> Contracts 
        {
            get 
            {
                return _contracts;
            }
            set 
            {
                _contracts = value;
                _contracts.LoadCompleted+=LoadContractData;
                OnPropertyChanged("Contracts");
            }
        }

        private DataServiceCollection<Note> _notes;
        public DataServiceCollection<Note> Notes 
        {
            get 
            {
                return _notes;
            }
            set 
            {
                _notes = value;
                _notes.LoadCompleted += LoadCommentData;
                OnPropertyChanged("Notes");
            }
        }

        public void LoadData() 
        {
            if (!Popup.IsOpen)
            {
                Popup.IsOpen = true;
                EnableButton.Invoke(false,null);
            }
            var c=new Contract();
            
            Contracts=new DataServiceCollection<Contract>();
            Notes=new DataServiceCollection<Note>();
            var contracts = (from contract in Context.Contracts.Expand("Owner").Expand("Opportunity").Expand("Department").Expand("BillingCustomer")
                            where contract.ContractId == ContractId && contract.IsDeleted == false
                            select contract);
            Contracts.LoadAsync(contracts);
        }

        public void LoadContractData(object sender, LoadCompletedEventArgs e) 
        {
            if (Contracts.Continuation != null) 
            {
                Contracts.LoadNextPartialSetAsync();
            }
            Notes.LoadAsync((from cust in Context.Notes.Expand("ModifiedBy") where cust.ObjectType == "Contract" && cust.ObjectId == ContractId && cust.IsDeleted == false orderby cust.CreatedOn descending select cust));
        } 

        public void LoadCommentData(object sender, LoadCompletedEventArgs e) 
        {
            if (Notes.Continuation != null) 
            {
                Notes.LoadNextPartialSetAsync();
            }
            Popup.IsOpen = false;
            EnableButton.Invoke(true,null);
        }
    }
}
